package dashboard

import (
	"embed"
	"fmt"
	"io/fs"
	"log"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/nick/vdamtools/apps/config"
	"github.com/nick/vdamtools/apps/dashboard/host"
	"github.com/nick/vdamtools/pkg/loggerv"
	"go.uber.org/zap"
)

//go:embed public/*
var staticFiles embed.FS

func Start() {
	r := gin.New()
	r.Use(gin.LoggerWithWriter(zap.NewStdLog(loggerv.GetLogger()).Writer())) // 记录所有路径的日志
	r.Use(gin.Recovery())

	dir, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}
	loggerv.GetLogger().Info("Current working directory:", zap.String("dir", dir))

	// 配置静态文件服务
	staticFS, err := fs.Sub(staticFiles, "public")
	if err != nil {
		loggerv.GetLogger().Fatal(err.Error())
	} else {
		loggerv.GetLogger().Info("fs.Sub success.")
	}

	// 提供静态文件服务
	r.StaticFS("/vdam", http.FS(staticFS))

	api := r.Group("/apis")
	{
		api.GET("/ping", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{"message": "pong"})
		})
		api.GET("/users", getUsers)
		api.POST("/users", createUser)

		api.GET("/cpus", getCpus)
		api.GET("/mem", getMem)
		api.POST("/host", host.Host)
		api.GET("/host", host.GetHost)
		api.GET("/lastIndexes", host.LastIndexes)
		api.GET("/getindexsByTimes", host.GetindexsByTimes)
	}

	// 捕获所有未匹配的路由，并返回index.html
	r.NoRoute(func(c *gin.Context) {
		c.FileFromFS("index.html", http.FS(staticFS))

		// if c.Request.URL.Path == "/vdam" || c.Request.URL.Path == "/vdam/" || len(c.Request.URL.Path) > 6 && c.Request.URL.Path[:6] == "/vdam" {
		// 	c.FileFromFS("index.html", http.FS(staticFS))
		// } else {
		// 	c.JSON(http.StatusNotFound, gin.H{"message": "Not Found"})
		// }
	})

	r.Run(fmt.Sprintf(":%d", config.GlobalConfig.Server.Port))
}
